package magnet.processor.instances.aspects.type;

import magnet.processor.MagnetProcessorEnv;
import magnet.processor.common.AptUtils;
import magnet.processor.common.ValidationException;
import magnet.processor.instances.parser.AttributeParser;
import magnet.processor.instances.parser.ParserInstance;

import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

public class TypeAttributeParser extends AttributeParser {

    private static volatile TypeAttributeParser INSTANCE;

    public static TypeAttributeParser INSTANCE() {
        synchronized (TypeAttributeParser.class) {
            if (INSTANCE == null) {
                synchronized (TypeAttributeParser.class) {
                    INSTANCE = new TypeAttributeParser();
                }
            }
        }
        return INSTANCE;
    }

    public TypeAttributeParser() {
        super("type");
    }

    @Override
    public <E extends Element> ParserInstance<E> parse(Scope<E> scope, AnnotationValue value) throws ValidationException {
        MagnetProcessorEnv env = scope.getEnv();
        TypeElement element = env.getElements().getTypeElement(value.getValue().toString());
        if (element != null) {
            if (scope.isTypeInheritanceEnforced()) {
                AptUtils.verifyInheritance(element,scope.getElement(),env.getTypes());
            }
            ParserInstance instance = scope.getInstance().copy();
            instance.setDeclaredType(element);
            return instance;
        }
        return scope.getInstance();
    }
}
